import {
  createPageData,
  deletePageData,
  editPageData,
  getPageListData
} from '@/service/main/system/system'
import { IRootState } from '@/store/types'
import { Module } from 'vuex'
import { ISystemState } from './types'

const pageUrlMap: any = {
  users: '/users/list',
  role: '/role/list',
  goods: '/goods/list',
  menu: '/menu/list'
}

const systemModule: Module<ISystemState, IRootState> = {
  namespaced: true,
  state() {
    return {
      usersList: [],
      usersCount: 0,
      roleList: [],
      roleCount: 0,
      goodsList: [],
      goodsCount: 0,
      menuList: [],
      menuCount: 0
    }
  },
  actions: {
    async getPageListAction({ commit }, payload: any) {
      //1.根据pageName获取url
      const pageName = payload.pageName as string
      const pageUrl = pageUrlMap[pageName]
      //2.发送请求获取数据
      const pageResult = await getPageListData(pageUrl, payload.queryInfo)
      // const { list, totalCount } = pageResult.data
      //3.将数据保存到state中
      commit(
        `change${
          pageName.slice(0, 1).toUpperCase() + pageName.slice(1).toLowerCase()
        }List`,
        pageResult.data
      )
    },
    async deletePageDataAction(context, payload: any) {
      const { pageName, id } = payload
      const pageUrl = `/${pageName}/${id}`
      const deleteRestlt = deletePageData(pageUrl)
      return deleteRestlt
    },
    // eslint-disable-next-line
    async createPageDataAction({ dispatch }, payload: any) {
      const { pageName, newData } = payload
      const pageUrl = `/${pageName}`
      await createPageData(pageUrl, newData)
    },
    // eslint-disable-next-line
    async editPageDataAction({ dispatch }, payload: any) {
      const { pageName, editData, id } = payload
      const pageUrl = `/${pageName}/${id}`
      await editPageData(pageUrl, editData)
    }
  },
  mutations: {
    changeUsersList(state, usersList: any) {
      state.usersCount = usersList.totalCount
      state.usersList = usersList.list
    },
    changeRoleList(state, roleList: any) {
      state.roleCount = roleList.totalCount
      state.roleList = roleList.list
    },
    changeGoodsList(state, goodsList: any) {
      state.goodsCount = goodsList.totalCount
      state.goodsList = goodsList.list
    },
    changeMenuList(state, menuList: any) {
      state.menuCount = menuList.totalCount
      state.menuList = menuList.list
    }
  },
  getters: {
    pageListData(state) {
      return (pageName: string) => {
        return (state as any)[`${pageName}List`]
      }
    },
    pageListCount(state) {
      return (pageName: string) => {
        return (state as any)[`${pageName}Count`]
      }
    }
  }
}

export default systemModule
